package com.yc.tomcat.core;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TomcatServer {
	protected boolean started = true;
	
	// 用来存放所有的session信息， 以jsessionid为键，每个客户端的session对象为值
	protected static Map<String, Session> sessions = new Hashtable<String, Session>();
	
	public void start() throws IOException {
		ServerSocket ssk = new ServerSocket(ContantInfo.PORT);
		
		// 创建项目部署路径
		File fl = new File(ContantInfo.BASE_PATH);
		if (!fl.exists()) {
			fl.mkdirs();
		}
		
		// TODO 启动一个精灵线程去清理session
		Thread thread = new Thread(new ClearSession());
		thread.setDaemon(true);
		thread.start();
		// TODO 扫描项目部署路径下所有项目里面的WEB-INF下的web.xml 看是否有配置servlet
		new ParseUrlPattern();
		// TODO 解析web.xml 文件获取扩展名对应的类型
		new ParseWebXml();
		// TODO 创建一个线程池去处理请求
		ExecutorService serviceThread = Executors.newFixedThreadPool(20);  // 创建一个固定大小的线程池 线程数为20
		Socket sk = null;
		
		// 循环监听来自客户端的请求
		while (started) {
			sk = ssk.accept();
			serviceThread.submit(new ServerService(sk));
		}
	}
}
